package ch.fusun.baron.basic.command;

import ch.fusun.baron.core.injection.Configure;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.map.Tile;
import ch.fusun.baron.map.api.GameMapService;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.player.api.Country;
import ch.fusun.baron.property.api.PropertyService;

/**
 * Annects the land for the specified player
 */
public class AnnectLandCommand extends MoneyTurnCommand {

	@Configure(value = "10")
	private int TURN_COST;
	@Configure(value = "10")
	private int MONEY;
	@Inject
	private transient GameMapService mapService;
	@Inject
	private transient PropertyService propertyService;

	private Tile tile;
	private Dynasty dynasty;
	private Country country;

	/**
	 * Injection constructor
	 */
	public AnnectLandCommand() {
		// injection
	}

	/**
	 * @param dynasty
	 *            The dynasty
	 * @param country
	 *            The country
	 * @param tile
	 *            The tile
	 */
	public AnnectLandCommand(Dynasty dynasty, Country country, Tile tile) {
		this.dynasty = dynasty;
		this.country = country;
		this.tile = tile;
	}

	@Override
	public boolean isAllowedImpl() {
		return !propertyService.isOwned(tile) && countryHasAdjacentTiles();
	}

	private boolean countryHasAdjacentTiles() {
		int width = mapService.getWidth();
		int height = mapService.getHeight();
		for (int i = -1; i < 2; i++) {
			for (int j = -1; j < 2; j++) {
				if (i * j == 0) {// Not diagonal, not the center itself
					Tile current = mapService.getTile((tile.getX() + i + width)
							% width, (tile.getY() + j + height) % height);
					if (country.equals(propertyService.getOwnership(current))) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public void executeImpl() {
		propertyService.setOwnership(country, tile);
	}

	@Override
	protected int getTurnCost() {
		return TURN_COST;
	}

	@Override
	protected Dynasty getDynasty() {
		return dynasty;
	}

	@Override
	protected int getMoneyCost() {
		return MONEY;
	}

}
